/*
 * Copyright 2010-2012 Susanta Tewari. <freecode4susant@users.sourceforge.net>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package commons.util;

import commons.util.base.Converter;

import java.util.Iterator;

/**
 * @author Susanta Tewari
 * @since Sep 1, 2011
 */
public class ConverterUtil {

    /**
     * Creates an iterable of output type from a given iterable of input type {@code I}
     * and an instance of converter.
     *
     * @param <I> input type
     * @param <O> output type
     * @param iterable input iterable to be converted
     * @param converter an instance of {@code Converter}. Converts an input type instance to its
     * corresponding output type instance
     * @return an iterable of the output type using the given converter
     */
    public static <I, O> Iterable<O> convert(Iterable<I> iterable,
            final Converter<I, O> converter) {

        final Iterator<I> itr = iterable.iterator();

        return new Iterable<O>() {

            @Override
            public Iterator<O> iterator() {

                return new Iterator<O>() {

                    @Override
                    public boolean hasNext() {

                        return itr.hasNext();
                    }

                    @Override
                    public O next() {

                        return converter.convert(itr.next());
                    }

                    @Override
                    public void remove() {

                        itr.remove();
                    }

                };
            }

        };
    }
}
